<?php
/**
 * 文件管理-运营文件（已停用）
 * (model)
 */
namespace App\Models\File;

use App\Func\UploadFile;
use App\Models\Basics\SysCountry;
use Illuminate\Database\Eloquent\Model;
class FileOperation extends Model
{
    protected $table = 'file_operation';

    protected $guarded = [];

    public function country()
    {
        return $this->belongsTo(SysCountry::class,'country_id');
    }

    public static $_fileType = [
        1 => 'Ads',
        2 => 'Business',
        3 => 'VideoCampaign',
        4 => 'BrandsCampaign',
        5 => 'DSP',
    ];

    /**
     * 解析状态
     */
    const STATUS_NO = 1; //未解析
    const STATUS_YES = 2; //已解析
    public static $_status = [
        self::STATUS_NO => '未解析',
        self::STATUS_YES => '已解析',
    ];

    public static function fileDir($time){
        return 'operation'.DIRECTORY_SEPARATOR.date('Ymd',$time);
    }

    public static function fileName($countryId,$fileType,$userId,$fileName){
        return $countryId.'-'.$fileType.'-'.$userId.'-'.$fileName;
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($model){
            if($model->status == 2){
                throw new \Exception('文件已解析无法删除');
            }
            $uf = UploadFile::getInit();
            $fileDir = self::fileDir(strtotime($model->file_date));
            $fileName = self::fileName($model->country_id,$model->file_type,$model->user_id,$model->file_name);
            $flag = $uf->delFile($fileDir.DIRECTORY_SEPARATOR.$fileName);
            if(!$flag){
                throw new \Exception('删除失败');
            }
        });
    }
}
